package com.forum.service.impl;

import com.forum.common.constant.PostConstants;
import com.forum.common.event.MessageEventPublisher;
import com.forum.common.event.PostAuditEvent;
import com.forum.common.exception.BusinessException;
import com.forum.mapper.PostAuditLogMapper;
import com.forum.mapper.PostMapper;
import com.forum.model.entity.Post;
import com.forum.model.entity.PostAuditLog;
import com.forum.model.vo.PostVO;
import com.forum.post.service.AutoAuditService;
import com.forum.service.PostAuditService;
import com.forum.service.PostService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 帖子审核服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PostAuditServiceImpl implements PostAuditService {
    
    private final PostMapper postMapper;
    private final PostService postService;
    // 假设我们已经创建了审核日志表和对应的Mapper
    private final PostAuditLogMapper postAuditLogMapper;
    // 注入消息事件发布服务
    private final MessageEventPublisher messageEventPublisher;
    
    @Autowired
    private AutoAuditService autoAuditService;
    
    @Override
    public List<PostVO> getPendingPosts() {
        List<Post> pendingPosts = postMapper.findPendingPosts();
        return convertToPostVOList(pendingPosts);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PostVO approvePost(Long postId, Long auditorId, String remark) {
        // 获取帖子
        Post post = postMapper.selectById(postId);
        if (post == null) {
            throw new BusinessException("帖子不存在");
        }
        
        // 检查帖子状态
        if (post.getStatus() != PostConstants.STATUS_PENDING) {
            throw new BusinessException("只能审核待审核状态的帖子");
        }
        
        // 更新帖子状态为已发布
        postMapper.updateStatus(postId, PostConstants.STATUS_PUBLISHED);
        
        // 记录审核日志
        PostAuditLog auditLog = new PostAuditLog();
        auditLog.setPostId(postId);
        auditLog.setAuditorId(auditorId);
        auditLog.setAction("approve");
        auditLog.setRemark(remark);
        auditLog.setCreatedAt(LocalDateTime.now());
        postAuditLogMapper.insert(auditLog);
        
        log.info("帖子审核通过: {}, 审核人: {}", postId, auditorId);
        
        // 向AI审核服务提交反馈
        if (post.getAiAuditResult() != null) {
            submitAuditFeedback(post, auditorId, "PASS", remark);
        }
        
        // 发送消息通知帖子作者
        try {
            PostAuditEvent event = PostAuditEvent.approved(
                auditorId,             // 发送者（审核人）
                post.getUserId(),      // 接收者（帖子作者）
                postId,                // 关联资源ID
                post.getTitle(),       // 帖子标题
                remark                 // 审核备注
            );
            messageEventPublisher.publishPostAuditEvent(event);
            log.info("审核通过消息发送成功");
        } catch (Exception e) {
            log.error("审核通过消息发送失败: {}", e.getMessage(), e);
            // 消息发送失败不影响主流程
        }
        
        // 返回更新后的帖子
        return postService.getPost(postId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PostVO rejectPost(Long postId, Long auditorId, String reason) {
        // 获取帖子
        Post post = postMapper.selectById(postId);
        if (post == null) {
            throw new BusinessException("帖子不存在");
        }
        
        // 检查帖子状态
        if (post.getStatus() != PostConstants.STATUS_PENDING) {
            throw new BusinessException("只能审核待审核状态的帖子");
        }
        
        // 更新帖子状态为已拒绝
        postMapper.updateStatus(postId, PostConstants.STATUS_REJECTED);
        
        // 记录审核日志
        PostAuditLog auditLog = new PostAuditLog();
        auditLog.setPostId(postId);
        auditLog.setAuditorId(auditorId);
        auditLog.setAction("reject");
        auditLog.setRemark(reason);
        auditLog.setCreatedAt(LocalDateTime.now());
        postAuditLogMapper.insert(auditLog);
        
        log.info("帖子审核拒绝: {}, 审核人: {}, 原因: {}", postId, auditorId, reason);
        
        // 向AI审核服务提交反馈
        if (post.getAiAuditResult() != null) {
            submitAuditFeedback(post, auditorId, "REJECT", reason);
        }
        
        // 发送消息通知帖子作者
        try {
            PostAuditEvent event = PostAuditEvent.rejected(
                auditorId,             // 发送者（审核人）
                post.getUserId(),      // 接收者（帖子作者）
                postId,                // 关联资源ID
                post.getTitle(),       // 帖子标题
                reason                 // 拒绝原因
            );
            messageEventPublisher.publishPostAuditEvent(event);
            log.info("审核拒绝消息发送成功");
        } catch (Exception e) {
            log.error("审核拒绝消息发送失败: {}", e.getMessage(), e);
            // 消息发送失败不影响主流程
        }
        
        // 返回更新后的帖子
        return postService.getPost(postId);
    }
    
    /**
     * 提交审核反馈到AI审核服务
     */
    private void submitAuditFeedback(Post post, Long adminId, String finalDecision, String feedback) {
        try {
            boolean isCorrect = finalDecision.equals(post.getAiAuditResult());
            autoAuditService.submitFeedback(
                post.getId(),
                adminId,
                post.getAiAuditResult(),
                finalDecision,
                isCorrect,
                feedback
            );
            log.info("AI审核反馈已提交: postId={}, adminId={}, aiDecision={}, finalDecision={}, isCorrect={}",
                post.getId(), adminId, post.getAiAuditResult(), finalDecision, isCorrect);
        } catch (Exception e) {
            log.error("提交AI审核反馈失败: {}", e.getMessage(), e);
            // 反馈提交失败不影响主流程
        }
    }
    
    @Override
    public List<PostVO> getPostsByStatus(Integer status) {
        List<Post> posts = postMapper.findPostsByStatus(status);
        return convertToPostVOList(posts);
    }
    
    @Override
    public List<PostVO> getUserAllPosts(Long userId) {
        List<Post> posts = postMapper.selectAllByUserId(userId);
        return convertToPostVOList(posts);
    }
    
    /**
     * 将帖子实体列表转换为VO列表
     */
    private List<PostVO> convertToPostVOList(List<Post> posts) {
        if (posts == null || posts.isEmpty()) {
            return new ArrayList<>();
        }
        
        return posts.stream()
            .map(post -> {
                PostVO postVO = new PostVO();
                BeanUtils.copyProperties(post, postVO);
                postVO.setCategoryName(post.getCategoryName());
                postVO.setAuthorName(post.getAuthorName());
                postVO.setAuthorAvatar(post.getAuthorAvatar());
                return postVO;
            })
            .collect(Collectors.toList());
    }
} 